<template>
  <div class="add-setmeal">
    <el-form :model="ruleForm" :rules="rules" ref="rulesForm">
        <el-form-item class="form-item">
            <el-form-item prop="setmealName" label="套餐名称：">
                <div class="name">
                    <el-input placeholder="请填写套餐名称" v-model="ruleForm.setmealName"></el-input>
                </div>
            </el-form-item>
            <el-form-item prop="category" label="套餐分类：">
                <div class="category">
                    <el-select placeholder="请选择套餐分类" v-model="ruleForm.category">
                        <el-option v-for="item in categoryOptions" :key="item.value" :label="item.label" :value="item.value"></el-option>
                    </el-select>
                </div>
            </el-form-item>
        </el-form-item>
        <el-form-item class="form-item" prop="price" label="价格：">
            <el-input placeholder="请设置套餐价格" v-model="ruleForm.price"></el-input>
        </el-form-item>
        <el-form-item class="form-item" label="菜品：">
            <div class="addDish-box" :class="{ active: isShowDishList }">
                <button type="button" class="addDishBtn" @click="openAddDishDialog">+ 添加菜品</button>
                <el-table v-if="isShowDishList" :data="selectDishList">
                    <el-table-column width="180" align="center" label="名称" prop="name"></el-table-column>
                    <el-table-column width="180" align="center" label="原价" prop="price"></el-table-column>
                    <el-table-column width="193" align="center" label="份数">
                        <template slot-scope="scope">
                            <el-input-number size="mini" :min="1" :max="99" v-model="scope.row.copies"></el-input-number>
                        </template>
                    </el-table-column>
                    <el-table-column width="180" align="center" label="操作">
                        <template slot-scope="scope">
                            <span @click="deleteSelectDish(scope.row.name)" class="delete">删除</span>
                        </template>
                    </el-table-column>
                </el-table>
            </div>
        </el-form-item>
        <el-form-item label="菜品图片：" class="form-item" prop="uploadPicUrl">
            <FileUpload @change="handleUploadSuccess" @click="deleteImg" :uploadPicUrl="ruleForm.uploadPicUrl" :headers="headers"></FileUpload>
        </el-form-item>
        <el-form-item class="form-item">
            <label class="img">套餐描述：</label>
            <el-input v-model="describe" type="textarea" rows="3" placeholder="套餐描述，最长200字"></el-input>
        </el-form-item>
    </el-form>
    <hr />
    <div class="footer">
        <el-button @click="$router.back()">取消</el-button>
        <el-button v-if="!isEditStatus" @click="handleSave(false)">保存</el-button>
        <el-button v-else @click="handleEdit" type="primary">保存</el-button>
        <el-button v-show="!isEditStatus" @click="handleSave(true)" type="primary">保存并继续添加</el-button>
    </div>
    <!-- 添加菜品弹窗 -->
    <el-dialog
     custom-class="dialog-add-dish"
     title="添加菜品"
     :show-close="false"
     :visible.sync="dialogDishVisible"
     width="55%">
        <template slot="title">
            <h4 class="title">添加菜品</h4>
            <el-input prefix-icon="el-icon-search" placeholder="请输入菜品名称进行搜索"></el-input>
        </template>
        <template>
            <div class="left-content">
                <div class="category-list">
                    <div @click="handleDishShow(item.id, key)" v-for="(item, key) in dishCategoryList" :key="item.id" :class="{ active: dishSidebarIndex ===  key}" class="category-item">
                        <span>{{ item.name }}</span>
                    </div>
                </div>
                <div class="dish-list">
                    <div v-for="item in dishList" :key="item.id" class="dish-item">
                        <el-checkbox @change="handleAddDish($event, item)" v-model="item.isChecked">
                            <span class="name">{{ item.name }}</span>
                            <span class="status">{{ item.status === 1 ? '起售' : '停售' }}</span>
                            <span class="price">{{ item.price }}</span>
                        </el-checkbox>
                    </div>
                </div>
            </div>
            <div class="right-content">
                <div class="head">
                    <span>已选菜品（{{ selectDishList.length }}）</span>
                </div>
                <div class="select-dish-list">
                    <div v-for="item in selectDishList" :key="item.id" class="select-dish-item">
                        <span class="name">{{ item.name }}</span>
                        <span class="price">￥ {{ item.price }}</span>
                        <img @click="deleteSelectDish(item.name)" src="@/assets/icons/btn_clean@2x.png" alt="">
                    </div>
                </div>
            </div>
        </template>
        <template slot="footer">
            <el-button @click="dialogDishVisible = false">取消</el-button>
            <el-button type="primary" @click="addDish">添加</el-button>
        </template>
    </el-dialog>
  </div>
</template>

<script>
import { addSetmeal, getSetmealDetail, editSetmeal } from '@/api/setmeal'
import { getDishList } from '@/api/dish'
import { getCategoryList } from '@/api/category'
import FileUpload from '@/components/FileUpload.vue'
import { getToken } from '@/utils/storage'
export default {
  name: 'AddSetmeal',
  components: {
    FileUpload
  },
  data () {
    const validateSetmealName = (rule, value, callback) => {
      const reg = /^[\u4e00-\u9fa5A-Za-z0-9]{2,20}$/
      if (!reg.test(value)) {
        callback(new Error('套餐名称输入不符，请输入2-20个字符'))
      }
      callback()
    }
    const validatePrice = (rule, value, callback) => {
      const reg = /^(0|[1-9]\d*)(\.\d{1,2})?$/
      if (!reg.test(value)) {
        callback(new Error('套餐价格格式有误，请输入大于零且最多保留两位小数的金额'))
      }
      callback()
    }
    return {
      categoryOptions: [],
      describe: '',
      headers: {
        Authorization: 'Bearer ' + getToken()
      },
      isShowDishList: false,
      dialogDishVisible: false,
      dishSidebarIndex: 0,
      dishCategoryList: [],
      dishList: [],
      selectDishList: [],
      ruleForm: {
        setmealName: '',
        category: '',
        price: '',
        uploadPicUrl: ''
      },
      rules: {
        setmealName: [
          { validator: validateSetmealName, required: true, message: '请输入套餐名称', trigger: 'blur' }
        ],
        category: [
          { required: true, message: '请选择套餐分类', trigger: 'change' }
        ],
        price: [
          { validator: validatePrice, required: true, message: '请设置套餐价格', trigger: 'blur' }
        ],
        uploadPicUrl: [
          { required: true, message: '菜品图片不能为空', trigger: 'change' }
        ]
      },
      isEditStatus: false,
      setmealDetail: []
    }
  },
  async created () {
    this.getSetmealCategory()
    this.getDishCategory()
    if (this.$route.query.id) {
      this.isEditStatus = true
      this.getSetmealDetail(this.$route.query.id)
    }
  },
  methods: {
    handleUploadSuccess (res) {
      this.ruleForm.uploadPicUrl = res
    },
    deleteImg () {
      this.ruleForm.uploadPicUrl = ''
    },
    // 获取菜品分类
    async getDishCategory () {
      const res = await getCategoryList({ type: 1 })
      if (res.code === 1) {
        this.dishCategoryList = res.data
      }
    },
    // 获取套餐分类
    async getSetmealCategory () {
      const res = await getCategoryList({ type: 2 })
      if (res.code === 1) {
        res.data.forEach(item => {
          this.categoryOptions.push({
            value: item.id,
            label: item.name
          })
        })
      }
    },
    // 根据分类ID获取菜品列表
    async getDishList (id) {
      const res = await getDishList({ categoryId: id })
      if (res.code === 1) {
        res.data.forEach(item => {
          item.isChecked = false
          item.copies = 1
        })
        // 如果有添加了的菜品，则检查当前查询的菜品列表，是否在数组有包含，如果包含则 checked 为true
        if (this.selectDishList.length) {
          this.selectDishList.forEach(dishItem => {
            if (res.data.find(item => item.name === dishItem.name)) {
              res.data.find(item => item.name === dishItem.name).isChecked = true
            }
          })
        }
        this.dishList = res.data
      }
    },
    // 获取套餐详情
    async getSetmealDetail (id) {
      const res = await getSetmealDetail(id)
      if (res.code === 1) {
        this.setmealDetail = res.data
        this.ruleForm.setmealName = res.data.name
        this.ruleForm.category = res.data.categoryId
        this.ruleForm.price = res.data.price
        this.ruleForm.uploadPicUrl = res.data.image
        this.describe = res.data.description
        this.selectDishList = res.data.setmealDishes
        this.isShowDishList = true
      }
    },
    // 切换分类，并获取分类对应的菜品
    handleDishShow (id, key) {
      this.dishSidebarIndex = key
      this.getDishList(id)
    },
    // 处理点击菜品添加到已选菜品数组中
    handleAddDish (flag, dishItem) {
      if (flag) {
        this.selectDishList.unshift({
          dish_id: dishItem.id,
          name: dishItem.name,
          copies: dishItem.copies,
          price: dishItem.price
        })
      } else {
        this.selectDishList.splice(this.selectDishList.indexOf(dishItem), 1)
      }
    },
    // 处理添加按钮的逻辑
    addDish () {
      if (this.selectDishList.length) {
        this.isShowDishList = true
      } else {
        this.isShowDishList = false
      }
      this.dialogDishVisible = false
    },
    handleSave (isContinue) {
      this.$refs.rulesForm.validate(async valid => {
        if (!valid) return

        const setmealDishes = []
        this.selectDishList.forEach(item => {
          setmealDishes.push({
            copies: item.copies,
            dishId: item.dish_id,
            name: item.name,
            price: item.price
          })
        })

        try {
          const res = await addSetmeal({
            categoryId: this.ruleForm.category,
            description: this.describe || null,
            image: this.ruleForm.uploadPicUrl,
            name: this.ruleForm.setmealName,
            price: this.ruleForm.price,
            setmealDishes: setmealDishes,
            status: 0
          })

          if (res.code === 1) {
            this.$message.success('操作成功')

            // 重置
            this.$refs.rulesForm.resetFields()
            this.describe = ''
            this.selectDishList = []
            this.isShowDishList = false

            // 返回
            if (!isContinue) {
              this.$router.back()
            }
          } else {
            this.$message.error(res.msg)
          }
        } catch (error) {
          this.$message.error(error.response.data.msg)
        }
      })
    },
    async handleEdit () {
      const setmealDishes = []
      this.selectDishList.forEach(item => {
        setmealDishes.push({
          id: item.id,
          setmealId: item.setmeal_id,
          dishId: item.dish_id,
          copies: item.copies,
          name: item.name,
          price: item.price
        })
      })
      console.log(setmealDishes)

      try {
        const res = await editSetmeal({
          categoryId: this.ruleForm.category,
          description: this.describe || null,
          id: this.setmealDetail.id,
          image: this.ruleForm.uploadPicUrl,
          name: this.ruleForm.setmealName,
          price: this.ruleForm.price,
          setmealDishes: setmealDishes,
          status: this.setmealDetail.status
        })
        if (res.code === 1) {
          this.$message.success('操作成功')
          this.$router.back()
        } else {
          this.$message.error(res.msg)
        }
      } catch (error) {
        this.$message.error(error.response.data.msg)
      }
    },
    // 从选择的菜品中删除
    deleteSelectDish (name) {
      this.selectDishList.splice(this.selectDishList.findIndex(item => item.name === name), 1)
      if (this.dishList[this.dishList.findIndex(item => item.name === name)]) {
        this.dishList[this.dishList.findIndex(item => item.name === name)].isChecked = false
      }
      if (this.selectDishList.length === 0) {
        this.isShowDishList = false
      }
    },
    openAddDishDialog () {
      this.dialogDishVisible = true
      this.getDishList(this.dishCategoryList[0].id)
      this.dishSidebarIndex = 0
    }
  }
}
</script>

<style lang="less" scoped>
.add-setmeal {
    background-color: #fff;
    padding: 20px;
    border-radius: 5px;

    ::v-deep .el-form {
        display: flex;
        flex-direction: column;

        .el-form-item__label {
          min-width: 180px;
          color: #000;
        }

        .form-item .el-form-item__content {
            display: flex;
            font-size: 14px;
            line-height: normal;

            .el-input {
                width: 350px;
            }

            .el-select .el-input {
                width: auto;
            }

            .el-textarea {
                width: 776px;
            }

            label {
                display: flex;
                align-items: center;
                justify-content: flex-end;
                min-width: 180px;
                height: 40px;
                padding-right: 5px;
            }

            > div {
                display: flex;
                align-items: center;
            }

            .addDish-box {
                display: flex;
                flex-direction: column;
                align-items: flex-start;

                &.active {
                    border: 1px solid #d8dde3;
                    background-color: #fafafb;
                    padding: 20px;
                }

                .addDishBtn {
                    color: #333;
                    border: 0;
                    outline: 0;
                    background-color: #ffc100;
                    border-radius: 5px;
                    padding: 0 20px;
                    height: 40px;
                    cursor: pointer;
                }

                .el-table {
                    margin-top: 20px;
                    border: 1px solid #ebeef5;

                    th {
                        color: #666;
                        font-size: 14;
                    }

                    td {
                        color: #333;
                        font-size: 13px;
                    }

                    .el-input-number .el-input {
                        width: auto;
                    }
                }

                .delete {
                    color: #f56c6c;
                    cursor: pointer;
                }
            }
        }

    }

    hr {
        border: 0;
        width: 100%;
        height: 1px;
        background-color: #f3f4f7;
        margin: 25px 0;
    }

    .footer {
        text-align: center;

        .el-button:nth-of-type(2) {
            background-color: #333;
            border-color: #333;
            color: #fff;
        }
    }

    ::v-deep .dialog-add-dish {
        .el-dialog__header {
            display: flex;
            align-items: center;
            justify-content: space-between;

            .el-input {
                width: 293px;
            }
        }

        .el-dialog__body {
            display: flex;
            padding: 20px;
            max-height: 400px;

            .left-content {
                flex: 2;
                display: flex;
                max-height: 400%;

                .category-list {
                    color: #333;
                    font-size: 14px;
                    font-weight: 600;
                    max-height: 100%;
                    overflow-y: auto;

                    .category-item {
                        text-align: center;
                        padding: 0 20px 0 0;
                        height: 40px;
                        line-height: 40px;
                        border-right: 2px solid #f4f4f4;
                        cursor: pointer;
                    }

                    .category-item.active {
                        color: #ffc200;
                        border-right: 2px solid #ffc200;
                    }
                }

                .dish-list {
                    flex: 2;
                    width: 100%;
                    max-height: 100%;
                    display: flex;
                    flex-direction: column;
                    align-items: center;
                    overflow-y: auto;

                    .dish-item {
                        display: flex;
                        align-items: center;
                        width: 90%;
                        padding: 10px;
                        font-size: 14px;
                        border: 1px solid #f4f4f4;
                        cursor: pointer;

                        &:not(:first-of-type) {
                            border-top: 0;
                            border-radius: 0;
                        }

                        &:first-of-type {
                            border-top-left-radius: 5px;
                            border-top-right-radius: 5px;
                        }

                        &:last-of-type {
                            border-bottom-left-radius: 5px;
                            border-bottom-right-radius: 5px;
                        }

                        .el-checkbox {
                            width: 100%;
                            display: flex;
                            align-items: center;
                        }

                        .el-checkbox__input.is-checked+.el-checkbox__label {
                            color: #333;
                        }

                        .el-checkbox__label {
                            width: 100%;
                            display: flex;
                            color: #333;

                            .name {
                                flex: 2;
                            }

                            .status,
                            .price {
                                flex: .5;
                                text-align: center;
                            }
                        }
                    }
                }
            }

            .right-content {
                flex: 1;
                padding: 0 10px 5px 10px;
                max-height: 100%;
                overflow-y: auto;

                .head {
                    color: #333;
                    font-weight: 600;
                    margin-bottom: 10px;
                }

                .select-dish-list {
                    display: flex;
                    flex-direction: column;
                    gap: 20px;

                    .select-dish-item {
                        display: flex;
                        align-items: center;
                        box-shadow: 0 0 6px 0 #eee;
                        border-radius: 5px;
                        padding: 10px;
                        background-color: #fff;
                        font-size: 14px;
                        color: #333;

                        .name {
                            flex: .8;
                        }

                        .price {
                            flex: 1;
                            text-align: center;
                        }

                        img {
                            width: 20px;
                            height: 20px;
                            cursor: pointer;
                        }
                    }
                }

            }
        }

        .el-dialog__footer {
            border-top: 1px solid #eee;
        }
    }

}
</style>
